package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chatlib.controller.MolianContactManager;
import com.pocketsweet.chatlib.controller.MolianContactManager.MoLianAgreeFridedListener;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.model.MLDate;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.adapter.NewApplyListAdapter;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_new_apply)
public class NewApply extends BaseActivity {

	@ViewInject(R.id.newApplyListview)
	private ListView newApplyListview;

	@ViewInject(R.id.mainHeader)
	private HeaderLayout header;

	@ViewInject(R.id.linBlank)
	private LinearLayout linBlank;

	public static LoadingDailog loading;
	private NewApplyListAdapter applyListAdapter;
	private List<MLDate> newApplyList = new ArrayList<MLDate>();
	private Context ctx;
	AVQuery<MLDate> querys;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		ctx = this;
		applyListAdapter = new NewApplyListAdapter(NewApply.this, newApplyList);
		newApplyListview.setAdapter(applyListAdapter);
		clear();
		MolianContactManager.getInstance().setMoLianAgreeFridedListener(
				new MoLianAgreeFridedListener() {

					@Override
					public void onAgressFail() {
						ToolKits.toast(ctx, "发送失败");
						loading.dismiss();
					}

					@Override
					public void onAgreeeSucess(String applyId, final View v) {

						AVQuery<MLDate> query = new AVQuery<MLDate>("MLDate");
						query.include("user");
						query.include("sponsor");
						query.getInBackground(applyId,
								new GetCallback<MLDate>() {

									@Override
									public void done(MLDate data, AVException e) {
										if (e == null) {
											if (data.getUser().getType() != C.USER_TYPE_NORMAL
													&& data.getSponsor()
															.getType() != C.USER_TYPE_NORMAL) {
												data.setStatus(C.DATE_STATUS_SUCCEED);
											} else if (data.getUser().getType() == C.USER_TYPE_NORMAL) {
												data.setStatus(C.DATE_STATUS_SUCCEED);
											} else {
												data.setStatus(C.DATE_STATUS_ACCEPT);
											}
											data.saveInBackground(new SaveCallback() {

												@SuppressLint("NewApi")
												@Override
												public void done(AVException e) {
													if (e == null) {
														loading.dismiss();
														TextView view = ((TextView) v);

														view.setTextColor(view
																.getResources()
																.getColor(
																		R.color.text_999));
														view.setBackground(null);
														view.setText("已同意");
													} else {
														loading.dismiss();
													}

												}
											});

										} else {
											loading.dismiss();
										}
									}
								});

					}
				});
		getNewApplyList();
		setHeaderFunction();
	}

	private void clear() {
		// Log.e("========", MLApplication.getInstance().getContactList()
		// .toString()
		// + " 111");
		// Log.e("========",
		// MLApplication.getInstance().getContactList()
		// .get(Constant.NEW_CHAT_APPLY).toString()
		// + " 222");
		EMConversation conversation = EMChatManager.getInstance()
				.getConversation(Constant.NEW_CHAT_APPLY);
		conversation.resetUnreadMsgCount();
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("忽略所有");
		header.setMiddleText("通话申请");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				NewApply.this.finish();
			}
		});
		header.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				if (newApplyList == null || newApplyList.size() == 0) {
					return;
				}
				final MyAlertDialog dialogCache = new MyAlertDialog(
						NewApply.this).builder().setMsg("是否忽略所有通话申请？")
						.setTitle("忽略所有")
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(View v) {

							}
						});
				dialogCache.setPositiveButton("确定", new OnClickListener() {
					@SuppressLint("SimpleDateFormat")
					@Override
					public void onClick(View v) {
						loading.setText("加载中");
						loading.show();
						querys = new AVQuery<MLDate>("MLDate");
						querys.whereEqualTo("user", UserService.getCurrentUser());
						querys.whereEqualTo("status", 0);
						querys.include("sponsor");
						querys.orderByDescending("createdAt");
						querys.deleteAllInBackground(new DeleteCallback() {

							@Override
							public void done(AVException e) {
								loading.dismiss();
								if (e == null) {
									newApplyList.clear();
									applyListAdapter.notifyDataSetChanged();
									linBlank.setVisibility(View.VISIBLE);
									// 删除与此人的会话
									EMChatManager.getInstance()
											.deleteConversation(
													Constant.NEW_CHAT_APPLY);
								} else {
									ToolKits.toast(NewApply.this, "网络错误，请重试");
								}
							}
						});

					}
				});
				dialogCache.show();
			}
		});
	}

	private void getNewApplyList() {
		loading = ToolKits.createLoadingDialog(NewApply.this, "获取中..");
		loading.show();

		querys = new AVQuery<MLDate>("MLDate");
		querys.whereEqualTo("user", UserService.getCurrentUser());
		querys.whereEqualTo("status", 0);
		querys.include("sponsor");
		querys.orderByDescending("createdAt");
		querys.findInBackground(new FindCallback<MLDate>() {

			@Override
			public void done(List<MLDate> mlDates, AVException e) {
				if (e == null) {
					if (mlDates.size() > 0) {
						linBlank.setVisibility(View.GONE);
						loading.dismiss();
						newApplyList = mlDates;
						applyListAdapter.setDatas(newApplyList);
						applyListAdapter.notifyDataSetChanged();
					} else {
						linBlank.setVisibility(View.VISIBLE);
						loading.dismiss();
					}
				} else {
					// 已加载完全部，取消loading
					// Log.e("====mlDateApplies", "nothing" + e.getMessage());

				}
			}

		});
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}
}
